package shiyan4;
public class ThreadSyncExample {
    // 共享资源类
    static class Counter {
        private int count = 0;
        
        // 同步方法：保证同一时间只有一个线程进入
        public synchronized void increment() {
            count++;
        }
        
        public int getCount() {
            return count;
        }
    }

    // 线程任务类：实现 Runnable 接口
    static class MyRunnable implements Runnable {
        private Counter counter;
        
        public MyRunnable(Counter counter) {
            this.counter = counter;
        }

        @Override
        public void run() {
            // 循环 1000 次调用共享资源的 increment 方法
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        }
    }

    // 主方法：测试多线程同步
    public static void main(String[] args) {
        // 创建共享资源
        Counter counter = new Counter();
        
        // 创建两个任务，共享同一个 Counter
        MyRunnable myRunnable1 = new MyRunnable(counter);
        MyRunnable myRunnable2 = new MyRunnable(counter);
        
        // 创建并启动线程
        Thread thread1 = new Thread(myRunnable1);
        Thread thread2 = new Thread(myRunnable2);
        thread1.start();
        thread2.start();

        // 等待线程执行完毕（避免主线程提前输出结果）
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出最终计数（正常应为 2000）
        System.out.println("Final count: " + counter.getCount());
    }
}
